package com.beiyan.mvc.repository.person;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.junit.Test;
import org.springframework.util.StringUtils;

import com.beiyan.mvc.model.test.Person;

public class PersonRepositoryImpl {

	@PersistenceContext
	private EntityManager entityManager;

	/**
	 * 拼装jpql实现分页查询Person
	 */
	@SuppressWarnings("unchecked")
	public List<Person> pageByUsernameLike(String username) {
		username = "%" + username + "%";
		int pageSize = 3;
		int pageNo = 1;
		String dataSql = "select p from Person p where 1 = 1";
		String countSql = "select count(p) from Person p where 1 = 1";

		if (!StringUtils.isEmpty(username)) {
			dataSql += " and p.username like ?1";
			countSql += " and p.username like ?1";
		}
		Query dataQuery = entityManager.createQuery(dataSql);
		Query countQuery = entityManager.createQuery(countSql);

		if (!StringUtils.isEmpty(username)) {
			dataQuery.setParameter(1, username);
			countQuery.setParameter(1, username);
		}
		System.out.println("totalCount: " + (long) countQuery.getSingleResult());
		dataQuery.setMaxResults(pageSize);
		dataQuery.setFirstResult((pageNo - 1) * pageSize);
		List<Person> persons = dataQuery.getResultList();
		return persons;
	}

	/**
	 * 使用CriteriaQuery实现查询
	 */
	@SuppressWarnings("unchecked")
	@Test
	public List<Person> findAllByNameLike(String name) {
		// 声明对象
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		CriteriaQuery<?> cq = cb.createQuery(Person.class);
		Root<Person> root = cq.from(Person.class);
		// 查询部分属性
		// todo:此处有问题，后续研究
		// tetch join and so on
		// cq.multiselect(root.get("username").alias("username"),root.get("id").alias("id"));
		// 构造条件
		Predicate condition = cb.like(root.get("username").as(String.class), cb.parameter(String.class, "username"));
		cq.where(condition);
		// 设置变量
		Query query = entityManager.createQuery(cq);
		query.setParameter("username", "%" + name + "%");
		List<Person> persons = query.getResultList();
		return persons;
	}
	
	@SuppressWarnings("unchecked")
	public List<Person> findPersonByNameLike(String name) {
		Query query = entityManager.createNamedQuery("findPersonByNameLike");
		query.setParameter(1, name);
		return query.getResultList();
		
	}
}
